package server

import (
	"epg/jmconf"
	"fmt"
	"os"
	"strconv"
	"sync"
	"time"
)

var (
	defaultMeasurement = "slowquery"
)

type slowLog struct {
	sync.Mutex
	Measurement string
	Host        string
	MaxTime     time.Duration
	logger      *os.File //the slow query log file
}

//newSlowLog new a slow query logger.
func newSlowLog(maxms int64, fname string) (*slowLog, error) {
	fd, err := os.OpenFile(fname, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0666)
	if err != nil {
		return nil, err
	}
	host := jmconf.Cfg.HostName
	if host == "" {
		host, _ = os.Hostname()
	}

	sl := &slowLog{
		Measurement: defaultMeasurement,
		Host:        host,
		MaxTime:     time.Duration(maxms) * time.Millisecond,
		logger:      fd,
	}
	return sl, nil
}

//log wirte the log as influxdb line protocol.
//e.g.: cpu,tag1=tagval1,tag2=tagval2 key1=val1,key2=val2,key3="" timestamp
//see https://docs.influxdata.com/influxdb/v0.13/write_protocols/line/
func (sl *slowLog) log(user, db, ip, node string, t time.Duration, sql string) {
	if sl.MaxTime > 0 && t >= sl.MaxTime {
		if db == "" {
			db = "nil"
		}
		if node == "" {
			node = "nil"
		}
		sql = strconv.Quote(sql)
		msg := fmt.Sprintf(`%s,host=%s,user=%s,db=%s,node=%s,ip=%s usetime=%d,sql=%s %d`+"\n",
			sl.Measurement, sl.Host, user, db, node, ip, t, sql, time.Now().UnixNano())
		sl.Lock()
		sl.logger.WriteString(msg)
		sl.Unlock()
	}
}
